package proyectoFC_2_3_3.koyicabuto.balloonOverlay;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import proyectoFC_2_3_3.koyicabuto.HttpRetriever;
import proyectoFC_2_3_3.koyicabuto.R;
import proyectoFC_2_3_3.koyicabuto.funciones.Funciones;
import proyectoFC_2_3_3.koyicabuto.funciones.FuncionesBaseDatos;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.maps.OverlayItem;

public class BalloonOverlayView extends FrameLayout{
	
	private static final String GOOGLE_GEOCODER = "http://maps.googleapis.com/maps/api/geocode/json?latlng=";
	private static final String BANDERA_EVENTO = "EVENTO";
	private static final String BANDERA_CONTACTO = "CONTACTO";
	
	private FuncionesBaseDatos funcionesBaseDatos = new FuncionesBaseDatos();
	
	private LinearLayout layout;
	private LinearLayout layoutDesc;
	private LinearLayout balloonMain;
	private TextView title;
	private TextView snippet;
	private ImageView foto;
	private Context context;
	private Long idItem;
	private Funciones funciones = new Funciones();
	private String bandera;
	private ImageView goPopUp;
	private TextView descripcionEvento;
	
	public BalloonOverlayView(final Context context, int balloonBottomOffset, String bandera) throws JSONException {
		super(context);
		setPadding(10, 0, 10, balloonBottomOffset);
		layout = new LinearLayout(context);
		layout.setVisibility(VISIBLE);
		this.context = context;
		this.bandera = bandera;
		
		final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflater.inflate(R.layout.balloon_overlay, layout);
		
		goPopUp = (ImageView)v.findViewById(R.id.balloon_go);
		
		if(this.bandera.equalsIgnoreCase(BANDERA_EVENTO)){
			goPopUp.setVisibility(VISIBLE);
		}else{
			goPopUp.setVisibility(INVISIBLE);
		}
		
		balloonMain = (LinearLayout)v.findViewById(R.id.balloon_main_layout);
		
		title = (TextView) v.findViewById(R.id.balloon_item_title);
		descripcionEvento = (TextView) v.findViewById(R.id.textDescripcion);
		snippet = (TextView) v.findViewById(R.id.balloon_item_snippet);
		
		foto = (ImageView)v.findViewById(R.id.balloon_photo);
		
		layoutDesc = (LinearLayout)v.findViewById(R.id.balloon_desc);
		layoutDesc.setVisibility(INVISIBLE);
		
		Uri u = getPhotoUri();
		if (u != null) {
			foto.setImageURI(u);			
		}
		
		final ImageView close = (ImageView) v.findViewById(R.id.balloon_close);
		close.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				
				Animation animation = AnimationUtils.loadAnimation(layout.getContext(), android.R.anim.slide_out_right);
				
				animation.setAnimationListener(new AnimationListener() {
			        public void onAnimationEnd(Animation arg0) {
			        	layout.setVisibility(GONE);
			        	
			        	if(BalloonOverlayView.this.bandera.equalsIgnoreCase(BANDERA_EVENTO)){
				        	goPopUp.setVisibility(VISIBLE);
							
							layoutDesc.setVisibility(INVISIBLE);
							balloonMain.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, (int)110));
			        	}
			        }

					public void onAnimationRepeat(Animation animation) {

						
					}

					public void onAnimationStart(Animation animation) {
					}
			    });
				
				layout.startAnimation(animation);				
			}
		});
		
		foto = (ImageView) v.findViewById(R.id.balloon_photo);
		
		if(this.bandera.equalsIgnoreCase(BANDERA_EVENTO)){
			goPopUp.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					goPopUp.setVisibility(INVISIBLE);
					
					layoutDesc.setVisibility(VISIBLE);
					Animation animationFadeIn = AnimationUtils.loadAnimation(layout.getContext(), android.R.anim.fade_in);
					animationFadeIn.setDuration(1500);
					layoutDesc.startAnimation(animationFadeIn);
					balloonMain.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));			
				}
			});
		}
		
		FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
		LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		params.gravity = Gravity.NO_GRAVITY;

		addView(layout, params);
	}

	
	public void setData(OverlayItem item) {
		
		layout.setVisibility(VISIBLE);
		if(item.getTitle() != null){
			title.setVisibility(VISIBLE);
			title.setText(item.getTitle());
		}else{
			title.setVisibility(GONE);
		}
		if(item.getSnippet() != null){
			snippet.setVisibility(VISIBLE);
			
			if(bandera.equalsIgnoreCase(BANDERA_CONTACTO)){
				double[] coordenadas = funciones.obtenerCoordenadasContacto(item.getSnippet(), this.getContext());
				
				String direccion = getAddressFromGPSData(coordenadas[1], coordenadas[0]);
				snippet.setText(direccion);
				
				idItem = Long.valueOf(item.getSnippet());
				Uri u = getPhotoUri();
				foto.setImageURI(u);
				BitmapDrawable drawable = (BitmapDrawable)foto.getDrawable();
				if(drawable != null){
					Bitmap bitmap = drawable.getBitmap();
					foto.setImageBitmap(getRoundedCornerBitmap(bitmap, 18));
				}else{
					drawable = (BitmapDrawable)this.getResources().getDrawable(R.drawable.silueta_tecnico);
					Bitmap bitmap = drawable.getBitmap();
					foto.setImageBitmap(getRoundedCornerBitmap(bitmap, 18));
				}
				
			}else if(bandera.equalsIgnoreCase(BANDERA_EVENTO)){
				
				idItem = Long.valueOf(item.getSnippet());
				
				double[] coordenadas = funciones.obtenerCoordenadasEvento(item.getSnippet(), this.getContext());
				
				String descripcion = funciones.obtenerDescripcionEvento(item.getSnippet(), this.getContext());
				descripcionEvento.setText(descripcion);
				
				String direccion = getAddressFromGPSData(coordenadas[1], coordenadas[0]);
				snippet.setText(direccion);
				
				Long idCreadorEvento = funciones.obtenerIdFotoCreadorEvento(item.getSnippet(), context);
				
				if(idCreadorEvento.compareTo(Long.valueOf(0)) != 0){
					//Estamos en el caso de que el creador es un contacto
					Uri u = getPhotoUri(idCreadorEvento);
					foto.setImageURI(u);
					BitmapDrawable drawable = (BitmapDrawable)foto.getDrawable();
					if(drawable != null){
						Bitmap bitmap = drawable.getBitmap();
						foto.setImageBitmap(getRoundedCornerBitmap(bitmap, 18));
					}else{
						drawable = (BitmapDrawable)this.getResources().getDrawable(R.drawable.silueta_tecnico);
						Bitmap bitmap = drawable.getBitmap();
						foto.setImageBitmap(getRoundedCornerBitmap(bitmap, 18));
					}
				}else{
					//Estamos en el caso de que es el usuario
					//Obtener idFotoPerfil
					int idFotoPerfil = obtenerFotoPerfilUsuario();
					
					BitmapDrawable drawable = null;
					
					//Obtenemos la foto del usuario
			        Bitmap thumbnails = MediaStore.Images.Thumbnails.getThumbnail(context.getContentResolver(), idFotoPerfil, 
		            														      MediaStore.Images.Thumbnails.MICRO_KIND, null);
			        if(thumbnails != null){
			        	Drawable d = new BitmapDrawable(thumbnails);
			        	drawable = (BitmapDrawable)d;
					}else{
						drawable = (BitmapDrawable)this.getResources().getDrawable(R.drawable.silueta_tecnico);
					}
					
					Bitmap bitmap = drawable.getBitmap();
					foto.setImageBitmap(getRoundedCornerBitmap(bitmap, 18));
				}
			}
			
		}else{
			//En el caso de que el Snippet sea nulo, quiere decir que el CONTACT_ID es nulo por lo que estamos hablando
			//del usuario del terminal
			
			//Obtener idFotoPerfil
			int idFotoPerfil = obtenerFotoPerfilUsuario();
			
			BitmapDrawable drawable = null;
			
			//Obtenemos la foto del usuario
	        Bitmap thumbnails = MediaStore.Images.Thumbnails.getThumbnail(context.getContentResolver(), idFotoPerfil, 
            														      MediaStore.Images.Thumbnails.MICRO_KIND, null);
	        if(thumbnails != null){
	        	Drawable d = new BitmapDrawable(thumbnails);
	        	drawable = (BitmapDrawable)d;
			}else{
				drawable = (BitmapDrawable)this.getResources().getDrawable(R.drawable.silueta_tecnico);;
			}
			
			Bitmap bitmap = drawable.getBitmap();
			foto.setImageBitmap(getRoundedCornerBitmap(bitmap, 18));
			
			double[] coordenadas = funciones.obtenerCoordenadasContacto(item.getSnippet(), this.getContext());
			String direccion = getAddressFromGPSData(coordenadas[1], coordenadas[0]);
			snippet.setText(direccion);
			
			snippet.setVisibility(VISIBLE);
		}
	}
	
	

	public String getAddressFromGPSData(double lat, double longi) {
			HttpRetriever agent = new HttpRetriever();
			String request = GOOGLE_GEOCODER + lat + "," + longi + "&sensor=false&language=es";
			String response = agent.retrieve(request);
			String formattedAddress = "";
			String calle = "";
			String ciudad = "";
			if (response != null) {
				Log.d("GeoCoder", response);
				try {
					JSONObject parentObject = new JSONObject(response);
					JSONArray arrayOfAddressResults = parentObject.getJSONArray("results");
					JSONObject addressItem = arrayOfAddressResults.getJSONObject(0);
					
					JSONArray arrayOfAddress = addressItem.getJSONArray("address_components");
					
					for(int i = 0; i < arrayOfAddress.length(); i++){
						JSONObject address = arrayOfAddress.getJSONObject(i);
						String tipo = address.getString("types");
						if(tipo.equalsIgnoreCase("[\"route\"]")){
							 calle = address.getString("long_name");
						}
						if(tipo.equalsIgnoreCase("[\"locality\",\"political\"]")){
							 ciudad = address.getString("long_name");
						}
					}					
					formattedAddress = calle + ", " + ciudad + ".";
					
				} catch (JSONException e) {

					e.printStackTrace();
				}

			}
			return formattedAddress;
		}
	
    public Uri getPhotoUri() {
    	if(idItem != null){
		    try {
		        Cursor cur = context.getContentResolver().query(
		                Data.CONTENT_URI,
		                null,
		                Data.CONTACT_ID + "=" + idItem + " AND "
		                        + ContactsContract.Data.MIMETYPE + "='"
		                        + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
		                null);
		        if (cur != null) {
		            if (!cur.moveToFirst()) {
		                return null; // no photo
		            }
		        } else {
		            return null; // error in cursor process
		        }
		    } catch (Exception e) {
		        e.printStackTrace();
		        return null;
		    }
		    Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, idItem);
		    return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
    	}
    	return null;
	}
    
    public Uri getPhotoUri(Long creadorEvento) {
    	if(creadorEvento != null){
		    try {
		        Cursor cur = context.getContentResolver().query(
		                Data.CONTENT_URI,
		                null,
		                Data.CONTACT_ID + "=" + creadorEvento + " AND "
		                        + ContactsContract.Data.MIMETYPE + "='"
		                        + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'", null,
		                null);
		        if (cur != null) {
		            if (!cur.moveToFirst()) {
		                return null; // no photo
		            }
		        } else {
		            return null; // error in cursor process
		        }
		    } catch (Exception e) {
		        e.printStackTrace();
		        return null;
		    }
		    Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, creadorEvento);
		    return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
    	}
    	return null;
	}
	
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels ) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
                .getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return output;
    }
	
	private int obtenerFotoPerfilUsuario(){
		int idFotoPerfil = Integer.valueOf(-1);
		
		SQLiteDatabase gruposDataBase = funcionesBaseDatos.conectaBaseDeDatos(context);
		String selectFoto = "SELECT USU_ID_FOTO_PERFIL FROM USUARIO ";
		try{
			if(gruposDataBase != null){
				
				Cursor cursor = gruposDataBase.rawQuery(selectFoto, null);
				if(cursor.moveToFirst()){
					do{
						idFotoPerfil = cursor.getInt(0);
					}while(cursor.moveToNext());
				}
				
				gruposDataBase.close();
			}
		}catch (Exception e) {
			System.out.println("Excepcion al consultar foto: " + e.getMessage());
		}

		return idFotoPerfil;
	}
}
